package com.david.videoapp

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import android.widget.Toast
import android.widget.VideoView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.david.core.normalreq.UrlHttpRequest
import com.david.core.normalreq.UrlHttpResponse
import com.david.core.utils.PreferenceUtils
import com.david.videoapp.adapter.ChannelAdapter
import com.david.videoapp.utils.LiveDataHelper
import org.json.JSONObject
import java.util.*

class MainActivity : AppCompatActivity(), ChannelAdapter.OnChannelSelectListener {
    private var channelAdapter: ChannelAdapter = ChannelAdapter()

    private lateinit var channelShowIcon:ImageView
    private lateinit var videoView:VideoView

    private lateinit var channels: RecyclerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)


        channels = findViewById(R.id.channels)
        channelShowIcon = findViewById(R.id.channel_show_icon)
//        mainBinding.channels.layoutManager = LinearLayoutManager(this)
        channels.adapter = channelAdapter
        channelAdapter.onChannelSelectListener = this

        videoView = findViewById(R.id.video_view)

        val lastPosition = PreferenceUtils.getInstance().getInt("lastPosition", 0)
        channelAdapter.currentPosition = lastPosition
        LiveDataHelper.getDataInstance().channels.let { channelAdapter.setChannels(it) }


        var scrollPosition = (lastPosition.minus(7))
        scrollPosition.let {
            if (scrollPosition < 0) {
                scrollPosition = 0
            }
            channels.scrollToPosition(scrollPosition)
        }

        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)


        //手机上隐藏显示频道逻辑
        channelShowIcon.setOnClickListener {
            if (channels.visibility == View.VISIBLE) {
                channels.visibility = View.GONE
                (channelShowIcon.layoutParams as ViewGroup.MarginLayoutParams).setMargins(0, 0, 0, 0)
            } else {
                channels.visibility = View.VISIBLE
                (channelShowIcon.layoutParams as ViewGroup.MarginLayoutParams).setMargins(0, 0, channels.width, 0)
            }
        }


        UrlHttpRequest().getRequest("http://load_star.gitee.io/htmlminifuncs/jsondata/liveshows" ,"", object :
            UrlHttpResponse{
            override fun onSuccess(result: String) {
                Log.e("result", result)
                val json = JSONObject(result)
                val arrays = json.getJSONArray("data")
                val resultList = ArrayList<ChannelBean>()
                for (index in 0 until arrays.length()) {
                    val item = arrays.getJSONObject(index)
                    val channelBean = ChannelBean()
                    channelBean.title = item.getString("title")
                    channelBean.url = item.getString("url")
                    resultList.add(channelBean)
                }
                Log.e("result", "channel size is " + resultList.size)

            }

            override fun onFail(msg: String) {
                Log.e("result", msg)
            }

        })

    }

    override fun onResume() {
        super.onResume()
        startPlay(channelAdapter.getCurrentChannel().url)
    }

    override fun onStop() {
        super.onStop()
        videoView.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
        videoView.stopPlayback()
    }

    override fun onChannelSelect(position: Int, channelBean: ChannelBean) {
        startPlay(channelBean.url)

        PreferenceUtils.getInstance().setInt("lastPosition", position)
    }

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        val keyCode = event!!.keyCode
        return if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT
            || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
            || keyCode == KeyEvent.KEYCODE_DPAD_UP
            || keyCode == KeyEvent.KEYCODE_DPAD_DOWN
            || keyCode == KeyEvent.KEYCODE_DPAD_CENTER
            || keyCode == KeyEvent.KEYCODE_ENTER
        ) {

            event.dispatch(this, null, null)
        } else super.dispatchKeyEvent(event)
    }

    /**电视遥控器按下事件处理*/
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_DPAD_UP -> //如果按下的是上键
            {
                if (channelAdapter.currentPosition > 0) {
                    channelAdapter.currentPosition -= 1
                    channelAdapter.notifyItemChanged(channelAdapter.currentPosition+1)
                    channelAdapter.notifyItemChanged(channelAdapter.currentPosition)
                    onChannelSelect(channelAdapter.currentPosition, channelAdapter.getCurrentChannel())

                    var scrollPosition = channelAdapter.currentPosition - 7
                    scrollPosition = if (scrollPosition < 0) 0 else scrollPosition

                    channels.scrollToPosition(scrollPosition)
                }

            }
            KeyEvent.KEYCODE_DPAD_DOWN -> //如果按下的是下键
            {
                if (channelAdapter.currentPosition < channelAdapter.itemCount) {
                    channelAdapter.currentPosition += 1
                    channelAdapter.notifyItemChanged(channelAdapter.currentPosition-1)
                    channelAdapter.notifyItemChanged(channelAdapter.currentPosition)
                    onChannelSelect(channelAdapter.currentPosition, channelAdapter.getCurrentChannel())


                    var scrollPosition = channelAdapter.currentPosition + 7
                    scrollPosition = if (scrollPosition >= channelAdapter.itemCount) (channelAdapter.itemCount - 1) else scrollPosition

                    channels.scrollToPosition(scrollPosition)
                }
            }

            KeyEvent.KEYCODE_DPAD_LEFT -> //如果按下的是左键
                channels.visibility = View.VISIBLE

            KeyEvent.KEYCODE_DPAD_RIGHT -> //如果按下的是右键
                channels.visibility = View.GONE
        }
        return super.onKeyDown(keyCode, event)
    }


    //防止连续切换
    var currentUrl = ""
    private val handler = @SuppressLint("HandlerLeak")
    object :Handler(Looper.getMainLooper(), null){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (videoView.isPlaying) {
                videoView.stopPlayback()
            }
            videoView.setVideoPath(currentUrl)
            videoView.start()
        }
    }

    private fun startPlay(url: String) {
        currentUrl = url
        handler.removeMessages(0)
        handler.sendEmptyMessageDelayed(0, 1000)
    }


    private var lastBackTime:Long = 0
    override fun onBackPressed() {
        if ((System.currentTimeMillis() - lastBackTime) > 1000) {
            Toast.makeText(this, "双击退出程序", Toast.LENGTH_LONG).show()
        } else {
            onBackPressedDispatcher.onBackPressed()
        }
        lastBackTime = System.currentTimeMillis()
    }
}
